package com.zsgeek.wisdchain.qutu.view.find;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zsgeek.wisdchain.qutu.BaseActivity;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.customControl.ClearEditText;
import com.zsgeek.wisdchain.qutu.base.event.PreferenceHelper;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.GetAdverListModel;
import com.zsgeek.wisdchain.qutu.base.model.QueryAdverListModel;
import com.zsgeek.wisdchain.qutu.popup.dialog.DialogUtil;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.tools.Utils;
import com.zsgeek.wisdchain.qutu.view.find.adapter.RecentSearchProductAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索
 */
public class SearchActivity extends BaseActivity {
    @BindView(R.id.search_bottom_tv)
    ClearEditText et_search_procdut;
    //    @BindView(R.id.recommendViewGroup)
//    RecommendViewGroup recommendViewGroup;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private RecentSearchProductAdapter recentSearchAdapter;
    private List<String> productSearchData = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recentSearchAdapter = new RecentSearchProductAdapter();
        recyclerView.setAdapter(recentSearchAdapter);

        et_search_procdut.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String searchStr = et_search_procdut.getText().toString().trim();
                if (TextUtils.isEmpty(searchStr)) {
                    ToastHelper.showToast("请输入内容");
                    return true;
                }
                //  业务逻辑
                queryAdverList(searchStr);
                //  键盘隐藏
                Utils.CloseInoutDecorView(SearchActivity.this);

                if (productSearchData != null) {
                    boolean isYours = false;
                    if (productSearchData.size() > 0) {
                        for (int i = 0; i < productSearchData.size(); i++) {
                            if (searchStr.equals(productSearchData.get(i))) {
                                isYours = true;
                                break;
                            }
                        }
                    }
                    if (!isYours) {
                        productSearchData.add(searchStr);
                        saveValue(new Gson().toJson(productSearchData));
                        recentSearchAdapter.notifyDataSetChanged();
                    }
                    return true;
                }
            }
            return false;
        });
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = PreferenceHelper.getInstance().getSharedPreferences();
        if (sharedPreferences != null) {
            String value = sharedPreferences.getString("productSearchData", null);
            if (value != null && value != "") {
                productSearchData = new Gson().fromJson(value, new TypeToken<List<String>>() {
                }.getType());
                recentSearchAdapter.setNewData(productSearchData);
            }
        }
    }

    @OnClick({R.id.cancel_tv, R.id.tv_clear_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel_tv:
                Utils.CloseInoutDecorView(SearchActivity.this);
                finish();
                break;
            case R.id.tv_clear_all:
                //清空
                if (productSearchData != null && productSearchData.size() > 0) {
                    productSearchData.clear();
                    saveValue("");
                    recentSearchAdapter.setNewData(null);
                    ToastHelper.showToast("清空成功");
                }
                break;
        }
    }

    /**
     * 搜索广告接口
     */
    private void queryAdverList(String key) {
        DialogUtil.createLoadingDialog(this, null);
        new JsonRequest(new JsonRequestCallBack() {
            @Override
            public void showResult(Object object, String taskId) {
                if (object instanceof GetAdverListModel) {
                    GetAdverListModel dataModel = (GetAdverListModel) object;
                    DialogUtil.closeLoadingDialog(SearchActivity.this);
                    if (dataModel.getCode() == 2000) {
                        ToastHelper.showToast("搜索成功");
                        startActivity(new Intent(SearchActivity.this, SearchResultActivity.class).putExtra("dataList", (Serializable) dataModel.getData()));
                    } else ToastHelper.showToast(dataModel.getMessage());
                }
            }

            @Override
            public void showError(String errorMsg, String taskId) {
                DialogUtil.closeLoadingDialog(SearchActivity.this);
                ToastHelper.showToast(errorMsg);
            }
        }).postJson(UrlPathHelper.getAdver() + "adver/queryAdverList?label=" + key, true, null, GetAdverListModel.class);
    }

    private void saveValue(String value) {
        SharedPreferences.Editor editor = PreferenceHelper.getInstance().getEditor();
        editor.putString("productSearchData", value);
        editor.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Utils.CloseInoutDecorView(SearchActivity.this);
    }
}
